package dpyNotepad;
import javax.microedition.lcdui.*;

public class MainMenu extends List {

	Notepad notepad;
	public static final String CHOOSE_FILE_FOLDER = "Choose file/folder";
	public static final String INPUT_FILENAME = "Input filename";
	public static final String CHOOSE_ENCODING = "Choose encoding";
	public static final String LOAD_FILE = "Load selected file";
	public static final String SAVE_FILE = "Save selected file";
	
	private static Image fileExplorer;
	private static Image inputFile;
	private static Image chooseEncoding;
	private static Image loadFile;
	private static Image saveFile;
	
	public MainMenu(String title, int type, Notepad notepad) {
		super(title, type);
		// TODO Auto-generated constructor stub
		this.notepad = notepad;
		
		this.setCommandListener(this.notepad);
		this.addCommand(this.notepad.openPadCmd);
		this.addCommand(this.notepad.exitCmd);
		
		try{
			if(fileExplorer == null){
				fileExplorer = Image.createImage("/fileExplorer.png");
			}
			if(inputFile == null){
				inputFile = Image.createImage("/inputFile.png");
			}
			if(chooseEncoding == null){
				chooseEncoding = Image.createImage("/encoding.png");
			}
			if(loadFile == null){
				loadFile = Image.createImage("/openFile.png");
			}
			if(saveFile == null){
				saveFile = Image.createImage("/saveFile.png");
			}
		}
		catch(Exception e){
		}
		
		this.append(CHOOSE_FILE_FOLDER, fileExplorer);
		this.append(INPUT_FILENAME, inputFile);
		this.append(CHOOSE_ENCODING, chooseEncoding);
		this.append(LOAD_FILE, loadFile);
		this.append(SAVE_FILE, saveFile);
	}
	
	public void setTicker(String folderPath){
		this.setTicker(new Ticker(folderPath));
	}
	
	public void handleCommand(){
		String command  = this.getString(this.getSelectedIndex());
		
		if(command == CHOOSE_FILE_FOLDER){
			this.notepad.goToFolderExplorerScreen();
		}
		else if(command == INPUT_FILENAME){
			this.notepad.goToInputFileNameScreen();
		}
		else if(command == CHOOSE_ENCODING){
			this.notepad.goToEncodingsExecute();
		}
		else if(command == SAVE_FILE){
			if(this.notepad.hasValidPath()){
				String text = this.notepad.getTextPageText();
				String path = this.notepad.getSavePath();

				boolean success = FolderExplorer.SaveTxtFile(text, path, this.notepad.encoding);
				if(success){
					this.notepad.showAlert("File saved successfully!");
				}
				else{
					this.notepad.showAlert("File wasn't saved successfully!");
				}
			}
			else{
				this.notepad.showAlert("Folder or file not selected!");
			}
		}
		else if(command == LOAD_FILE){
			if(this.notepad.hasValidPath()){
				String path = this.notepad.getSavePath();

				String text = FolderExplorer.LoadTxtFile(path, this.notepad.encoding);
				this.notepad.setTextPageText(text);
				this.notepad.goToNotepadExecute();
			}
			else{
				this.notepad.showAlert("Folder or file not selected!");
			}			
		}
	}

}
